//
//  EditSettingsViewController.m
//  FreeSWITCH_Console
//
//  Created by Christopher Danielson on 4/6/09.
//  Copyright 2009 MaxPowerSoft, LLC. All rights reserved.
//

#import "EditSettingsViewController.h"
#import "UserSetting.h"
#import "SwitchViewController.h"
#import "MainMenuViewController.h"

@implementation EditSettingsViewController

@synthesize userSetting;
@synthesize fieldLabels;
@synthesize tempValues;
@synthesize textFieldBeingEdited;
@synthesize tableView;

// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}

-(void) showAlert:(NSString *)str {
	NSString *message = [[NSString alloc] initWithFormat:@"%@", str];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
													message:message
												   delegate:nil
										  cancelButtonTitle:@"Ok"
										  otherButtonTitles:nil];
	[alert show];
	[message release];
	[alert release];	
}

-(IBAction)cancel:(id)sender{
	[self.svc mainMenuFromSettingsView];
}

- (IBAction)save:(id)sender
{
	if (textFieldBeingEdited != nil)
	{
		NSNumber *tfKey= [[NSNumber alloc] initWithInt:textFieldBeingEdited.tag];
		[tempValues setObject:textFieldBeingEdited.text forKey:tfKey];
		[tfKey release];
	}
	NSString *strPort;
	for (NSNumber *key in [tempValues allKeys])
	{
		switch ([key intValue]) {
			case kNameRowIndex:
				userSetting.name = [tempValues objectForKey:key];
				break;
			case kHostRowIndex:
				userSetting.host = [tempValues objectForKey:key];
				break;
			case kPortRowIndex:
				strPort = [tempValues objectForKey:key];
				userSetting.port = [strPort intValue];
				break;
			case kPasswordRowIndex:
				userSetting.password = [tempValues objectForKey:key];
			default:
				break;
		}
	}
	if ([userSetting.name length] < 1) {
		[self showAlert:@"Invalid name specified."];
	}
	else if ([userSetting.host length] < 1) {
		[self showAlert:@"Invalid host specified."];
	} else {
		[self.switchViewController.mainMenuViewController addObjectToPersistentData:userSetting];
		[self.switchViewController mainMenuFromSettingsView];
	}
}

-(IBAction)textFieldDone:(id)sender
{
	UITableViewCell *cell = (UITableViewCell *)[[(UIView *)sender superview] superview];
	UITableView *table = (UITableView *)[cell superview];
	NSIndexPath *textFieldIndexPath = [table indexPathForCell:cell];
	NSUInteger row = [textFieldIndexPath row];
	row++;
	if (row >= kNumberOfEditableRows)
		row = 0;
	NSUInteger newIndex[] = {0, row};
	NSIndexPath *newPath = [[NSIndexPath alloc] initWithIndexes:newIndex length:2];
	UITableViewCell *nextCell = [self.tableView cellForRowAtIndexPath:newPath];
	UITextField *nextField = nil;
	for (UIView *oneView in nextCell.contentView.subviews)
	{
		if ([oneView isMemberOfClass:[UITextField class]])
			nextField = (UITextField *)oneView;
	}
	[nextField becomeFirstResponder];
}

- (void)viewDidLoad {
	NSArray *array = [[NSArray alloc] initWithObjects:@"Name:", @"Host:", @"Port:", @"Password:", nil];
	self.fieldLabels = array;
	[array release];
		
	NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
	self.tempValues = dict;
	[dict release];
	
	self.userSetting = [[UserSetting alloc] initWithName:@"" host:@"" port:8021 password:@""];// [self.list objectAtIndex:row];
	
	tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 45.0f, 320.0f, 460.0f) style:UITableViewStyleGrouped];
	[tableView setDelegate:self];
	[tableView setDataSource:self];
	
	[self.view insertSubview:tableView aboveSubview:self.view];
	
	[super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

#pragma mark Table view methods

/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return kNumberOfEditableRows;
}
*/

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return kNumberOfEditableRows;
}

- (void) resetTable {
	[tableView reloadData];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *UserSettingCellIdentifier = @"UserSettingCellIdentifier";
	
	UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:UserSettingCellIdentifier];
	if (cell == nil) {
		
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero 
									   reuseIdentifier:UserSettingCellIdentifier] autorelease];
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 25)];
		label.textAlignment = UITextAlignmentLeft;
		label.tag = kLabelTag;
		label.font = [UIFont boldSystemFontOfSize:14];
		[cell.contentView addSubview:label];
		[label release];
		
		UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(90, 12, 200, 25)];
		textField.clearsOnBeginEditing = NO;
		[textField setDelegate:self];
		//textField.returnKeyType = UIReturnKeyDone;
		[textField addTarget:self 
					  action:@selector(textFieldDone:) 
			forControlEvents:UIControlEventEditingDidEndOnExit];
		[cell.contentView addSubview:textField];
	}
	NSUInteger row = [indexPath row];
	
	UILabel *label = (UILabel *)[cell viewWithTag:kLabelTag];
	UITextField *textField = nil;
	for (UIView *oneView in cell.contentView.subviews)
	{
		if ([oneView isMemberOfClass:[UITextField class]])
			textField = (UITextField *)oneView;
	}
	
	label.text = [fieldLabels objectAtIndex:row];
	if (row == kPortRowIndex)
		textField.text = @"8021";
	else
		textField.text = @"";
	/*
	NSNumber *rowAsNum = [[NSNumber alloc] initWithInt:row];
	switch (row) {
		case kNameRowIndex:
			if ([[tempValues allKeys] containsObject:rowAsNum])
				textField.text = [tempValues objectForKey:rowAsNum];
			else
				textField.text = userSetting.name;
			break;
		case kHostRowIndex:
			if ([[tempValues allKeys] containsObject:rowAsNum])
				textField.text = [tempValues objectForKey:rowAsNum];
			else
				textField.text = userSetting.host;
			break;
		case kPortRowIndex:
			if ([[tempValues allKeys] containsObject:rowAsNum])
				textField.text = [tempValues objectForKey:rowAsNum];
			else
				textField.text = [NSString stringWithFormat:@"%d", userSetting.port];
			break;
		case kPasswordRowIndex:
			if ([[tempValues allKeys] containsObject:rowAsNum])
				textField.text = [tempValues objectForKey:rowAsNum];
			else
				textField.text = userSetting.password;
		default:
			break;
	}
	 */
	if (textFieldBeingEdited == textField)
		textFieldBeingEdited = nil;
	
	textField.tag = row;
	//[rowAsNum release];
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
	self.textFieldBeingEdited = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
	NSNumber *tagAsNum = [[NSNumber alloc] initWithInt:textField.tag];
	[tempValues setObject:textField.text forKey:tagAsNum];
	[tagAsNum release];
}

- (void)dealloc {
	[textFieldBeingEdited release];
	[tempValues release];
	[userSetting release];
	[fieldLabels release];
	[tableView release];
    [super dealloc];
}

@end
